package butang.jvm.classloader.broken;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * ClassName: MyBreajClassLoader
 * Package: butang.jvm.classloader.broken
 * Description:
 *
 * @Author BuTang
 * @Create 2024/1/20 16:32
 * @Version 1.0
 */
public class MyClassLoader extends ClassLoader{
    /**
     * 负责加载的类所属目录
     */
    public String classPath;

    /**
     * 包名
     */
    public String packageName;

    public MyClassLoader(String packageName, String classPath) {
        this.packageName = packageName;
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) {
        //获取字节码完整路径
        String fileName = classPath + name + ".class";
        ByteArrayOutputStream baos = null;
        BufferedInputStream bis = null;
        try {
            //获取输入流
            bis = new BufferedInputStream(new FileInputStream(fileName));
            //获取输出流
            baos = new ByteArrayOutputStream();

            //读取数据写入输出流
            int len;
            byte[] data = new byte[1024];
            while ((len = bis.read(data)) != -1) {
                baos.write(data, 0, len);
            }
            //获取内存中完整的字节素组数据
            byte[] byteCodes = baos.toByteArray();
            //通过调用defineClass 方法将字节数组转换为class的实例
            return defineClass(packageName + "." + name, byteCodes, 0, byteCodes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
